<?php
namespace app\admin\controller\log;


use app\admin\controller\Base;
use app\common\model\PayWithdraw as models;
use app\common\traites\PublicCrudTrait;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\common\model\SysConfig;
use think\facade\Queue;

class PayWithdraw extends Base
{
    protected $model;
    use PublicCrudTrait;

    /**
     * 提现控制器
     */
    public function initialize()
    {
        $this->model = new models();
      //  parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     */
    public function index()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        //查询搜索条件
        $post = $this->request->post();
        $map=[];
        $date=[];
        $map [] = ['a.money_type', '=','money_balance'];
        isset($post['user_name']) && $map [] = ['b.user_name', 'like', '%' . $post['user_name'] . '%'];
        isset($post['status'])&& $post['status']!='' && $map [] = ['a.status', '=',intval($post['status'])];
        isset($post['type']) && $map [] = ['a.type', '=',intval($post['type'])];
        isset($post['agents']) && $post['agents']!='' && $map[]= ['b.market_uid', '=',$post['agents']];
        if (isset($post['start']) && isset($post['end'])) {
            $date['start'] = $post['start'];
            $date['end'] = $post['end'];
        }
        $list = $this->model->page_list($map,$limit, $page,$date);
        return $this->success($list);
    }

    /**
     * 通过
     * */
    public function pass(){
        //过滤数据
        $postField = 'id';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        //检测订单
        $find = $this->model->where('id','in',$post['id'])->where('status',0)->select()->toArray();
        if (!$find) return $this->failed('该提现订单已处理或不存在');
        foreach ($find as $k=>$v){
            Db::startTrans();
            try {
                Db::name('common_user')->where('id',$v['uid'])->inc('money_all_withdraw',$v['money'])->update();
                $data['status']=1;
                $data['success_time']=date('Y-m-d H:i:s');
                $data['admin_uid']= session('admin_user')['id'];
                //执行修改数据
                $this->model->where('id',$v['id'])->save($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                // 验证失败 输出错误信息
                   \think\facade\Log::write('批量提现通过错误id：'.$v['id'].'，错误信息：'.json_encode($e->getMessage()),'notice');
                continue;
            }
        }
        return $this->success([]);
    }
    /**
     *
     * 线上还是线下打款
     * */
    public function is_line()
    {
        //过滤数据
        $postField = 'id,is_online';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        //检测订单
        $find = $this->model->where('id', (int)$post['id'])->where('status',1)->where('is_online',0)->find();
        // 执行线上打款接口 开始 应老板需求新增

        $post['line_time']=date('Y-m-d H:i:s');
        $post['line_admin_uid']= session('admin_user')['id'];
        $post['is_online']= $post['is_online']==1?1:2;

        if ($post['is_online'] == 1){
            $cashOrderInfo = $find->toArray();
            $this->daifu($cashOrderInfo);
            // 更新 状态 
    		$res=$this->model->update($post);
    		if($res){
    			return $this->success([]);
    		}else{
    		    return $this->failed('线上打开失败');
    		}
    		
        }else{
            $res=$this->model->update($post);
    		if($res){
    			return $this->success([]);
    		}else{
    		    return $this->failed('线下打开失败');
    		}
        }
    }
	
	/**
	 * 提现记录
	 * */
	 public function daifu($info){
		$SysConfig=new SysConfig();

		//支付地址
		$api_address=$SysConfig->where('name','admin_address')->value('value');
		 //前端地址
		$web_address=$SysConfig->where('name','web_address')->value('value');
		$daifuData = array();
		$daifuData['merchant']='88006';
		$daifuData['total_amount'] = $info['money_actual']; // Number
		$daifuData['callback_url'] = $api_address.'/home/back/daiFuBack';
		$daifuData['order_id'] = $info['order_on'];
		$daifuData['bank'] = $info['u_bank_name'];
		$daifuData['bank_card_name'] = $info['u_bank_user_name'];
		$daifuData['bank_card_account'] = $info['u_bank_card']; // Number
		$daifuData['bank_card_remark'] = 'no';
		$daifuData['sign']=verifySignApplet($daifuData);
	
		$url='https://apicloud.gcash.cash/api/daifu';
		$curl_res=curl_post($url,$daifuData);
		Log::write('代付信息：'.$curl_res,'notice');
		if ($curl_res){
		    $curls_res=json_decode($curl_res,true);
		    if ($curls_res['status']==1){
		      //  return show(json_encode($curls_res['message']),1);
		    }else{
		        return $this->failed(json_encode($curls_res['message']));
		    }
		}else{
		    return show([],config('ToConfig.http_code.error'),'Invalid payment link');
		} 
	 }
    /**
     *
     * 拒绝
     * */
    public function refuse(){
        //过滤数据
        $postField = 'id,msg';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        //检测订单
        $find = $this->model->where('id','in',$post['id'])->where('status',0)->select()->toArray();
        if (!$find) return $this->failed('该提现订单已处理或不存在');

        foreach ($find as $k=>$v){
            $data['money']=$v['money'];
            $data['id']=$v['id'];
            $data['uid']=$v['uid'];
            // $data['type']=$v['type'];
            $data['admin_uid']= session('admin_user')['id'];
            Queue::push("app\job\CashRefuseQueue", json_encode($data), "CashOKJobQueue"); // 加入拒绝队列
        }
        return $this->success([]);
    }
        /**
     * 修改金额
     * */
    public function amount_edit(){
        //过滤数据
        $postField = 'id,money_fee,money_actual';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        //检测订单
          $find = $this->model->where('id',$post['id'])->where('status',0)->find();
        if (!$find) return $this->failed('该提现订单已处理或不存在');
        if ((!isset($post['money_fee']) && !is_numeric($post['money_fee'])) || (!isset($post['money_actual']) && !is_numeric($post['money_actual']))){
            return $this->failed('请传递有效参数');
        }
        $res=$this->model->update($post);
        if ($res){
            return $this->success([]);
        }else{
            return $this->failed('操作失败');
        }
    }

}